package com.nrgedge;

import info.magnolia.cms.beans.config.DefaultVirtualURIMapping;
import info.magnolia.cms.util.ContentUtil;
import info.magnolia.module.templatingkit.functions.STKTemplatingFunctions;
import info.magnolia.module.templatingkit.sites.Site;
import info.magnolia.objectfactory.Components;
import info.magnolia.repository.RepositoryConstants;

public class VanityUrlVirtualURIMapping extends DefaultVirtualURIMapping {

	private String configPath;
	
	@Override
	public MappingResult mapURI(String uri) {

		String parentPath = configPath.substring(PathHelper.nthLastIndexOf(configPath, '/', 3) + 1, configPath.lastIndexOf('/'));
		Site site = Components.getComponent(STKTemplatingFunctions.class).site();
		
        if ((site == null || parentPath.equals(site.getName())) && isValidURI(uri)) {
			MappingResult r = new MappingResult();
			r.setLevel(1);
			r.setToURI("forward:" + this.getToURI());
			return r;
		}

		return null;
	}

	@SuppressWarnings("deprecation")
	private boolean isValidURI(String uri) {
		return getFromURI() != null && 
				!getFromURI().startsWith("/.") && 
				ContentUtil.getContent(RepositoryConstants.WEBSITE, getFromURI()) == null && 
				getFromURI().equals(uri);
	}

	public String getConfigPath() {
		return configPath;
	}

	public void setConfigPath(String configPath) {
		this.configPath = configPath;
	}

}
